package com.cqhilink.api.common.utils.security.des;



import com.cqhilink.api.common.utils.security.base64.Base64Encod;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * 生成des密匙
 * Created by wangzhen on 2016/6/6.
 */
public class CreateDESKey {
    /**
     * 生成一个密匙
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String genKeyDES() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        keyGenerator.init(56);
        SecretKey secretKey = keyGenerator.generateKey();
        String base64Str = Base64Encod.byte2base64(secretKey.getEncoded());
        return base64Str;
    }

    /**
     * 将密匙转换成SecretKey对象
     *
     * @param base64Key
     * @return
     * @throws IOException
     */
    public static SecretKey loadKeyDES(String base64Key) throws IOException {
        byte[] bytes = Base64Encod.base642byte(base64Key);
        SecretKey secretKey = new SecretKeySpec(bytes, "DES");
        return secretKey;
    }
}
